import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { RootState } from '@/redux/store';
import { getMyCourses } from '@/services/course';
import { Course } from '@/types';
import '@/styles/pages/dashboard.scss';

const Dashboard = () => {
  const { teacher } = useSelector((state: RootState) => state.auth);
  const [courses, setCourses] = useState<Course[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchCourses = async () => {
      try {
        setLoading(true);
        const res = await getMyCourses();
        console.log('Dashboard获取课程响应:', res);
        
        // 处理不同返回格式的数据
        if (res && (res.code === 0 || res.code === 2000)) {
          if (res.data && Array.isArray(res.data.courses)) {
            setCourses(res.data.courses);
            console.log('成功设置课程:', res.data.courses);
          } else if (res.data && typeof res.data === 'object') {
            // 尝试从data中提取课程数据
            const extractedCourses = Object.values(res.data).find(Array.isArray);
            if (extractedCourses) {
              setCourses(extractedCourses);
              console.log('成功提取并设置课程列表:', extractedCourses);
            } else {
              setCourses([]);
              console.warn('无法提取课程数据:', res.data);
            }
          } else {
            setCourses([]);
            console.warn('课程数据为空或格式不匹配:', res.data);
          }
        } else {
          console.error('获取课程列表失败:', res.message || '未知错误');
          setCourses([]);
        }
      } catch (err) {
        console.error('获取课程列表失败', err);
        setCourses([]);
      } finally {
        setLoading(false);
      }
    };

    fetchCourses();
  }, []);

  return (
    <div className="dashboard-container">
      <div className="welcome-section">
        <h1>欢迎回来，{teacher?.name}</h1>
        <p>智慧课堂教师端 - 让课堂管理更轻松</p>
      </div>

      <div className="dashboard-grid">
        <div className="dashboard-card">
          <div className="card-header">
            <h2>我的课程</h2>
            <Link to="/courses" className="more-link">查看更多</Link>
          </div>
          <div className="card-content">
            {loading ? (
              <div className="loading">加载中...</div>
            ) : courses.length > 0 ? (
              <ul className="course-list">
                {courses.slice(0, 3).map((course) => (
                  <li key={course.id} className="course-item">
                    <Link to={`/courses/${course.id}`}>{course.name}</Link>
                    <span className="course-desc">{course.description}</span>
                  </li>
                ))}
              </ul>
            ) : (
              <div className="empty-data">
                <p>暂无课程</p>
                <Link to="/courses" className="btn btn-primary">
                  添加课程
                </Link>
              </div>
            )}
          </div>
        </div>

        <div className="dashboard-card">
          <div className="card-header">
            <h2>快捷操作</h2>
          </div>
          <div className="card-content">
            <div className="quick-actions">
              <Link to="/courses" className="quick-action-item">
                <div className="action-icon course-icon"></div>
                <span>课程管理</span>
              </Link>
              <Link to="/students" className="quick-action-item">
                <div className="action-icon student-icon"></div>
                <span>学生管理</span>
              </Link>
              <Link to="/sign-in" className="quick-action-item">
                <div className="action-icon signin-icon"></div>
                <span>签到管理</span>
              </Link>
            </div>
          </div>
        </div>
      </div>

      <div className="dashboard-card full-width">
        <div className="card-header">
          <h2>系统公告</h2>
        </div>
        <div className="card-content">
          <div className="announcement">
            <div className="announcement-item">
              <h3>系统升级通知</h3>
              <p>尊敬的老师，智慧课堂系统将于近期进行升级，届时会增加更多实用功能，敬请期待！</p>
              <span className="announcement-date">2023-06-01</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard; 